package com.menggudf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.menggudf.entity.Members;

@Repository
public class MembersDao {

    private static final Log log = LogFactory.getLog(MembersDao.class);

    @PersistenceContext(unitName = "medicalUnit")
    private EntityManager entityManager;

    public void persist(Members transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(Members persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public Members merge(Members detachedInstance) {
        try {
            Members result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Members findById(Integer id) {
        try {
            Members instance = entityManager.find(Members.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List<Members> getMembersByUserCode(String userCode) {
        try {
            StringBuffer sqld = new StringBuffer("from Members m where m.userCode=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, userCode);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getMembersByUserCode fail",e);
            throw e;
        }
    }

    public Members getMembersByRoleCode(String currRole) {
        try {
            StringBuffer sqld = new StringBuffer("from Members m where m.roleCode=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, currRole);
            List<Members> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("getMembersByRoleCode fail",e);
            throw e;
        }
    }
}
